package com.canal.admin.service;

import com.canal.admin.entity.TokenBasedAuthentication;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.www.NonceExpiredException;

/**
 * @author Administrator
 * @description
 * @date 2019年03月17 14:14
 */
public class TokenBasedAuthenticationProvider implements AuthenticationProvider {

    private UserTokenService userTokenService;

    public TokenBasedAuthenticationProvider(UserTokenService userTokenService) {
        this.userTokenService = userTokenService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String token = ((TokenBasedAuthentication)authentication).getToken();
        if(!userTokenService.tokenIsNotExpired(token)) {
            throw new NonceExpiredException("Token expires");
        }
        UserDetails userDetails = userTokenService.getUserLoginInfo(token);
        if(userDetails == null) {
            throw new NonceExpiredException("Token expires");
        }
        TokenBasedAuthentication tokenBasedAuthentication = new TokenBasedAuthentication(userDetails,token,userDetails.getAuthorities());
        return tokenBasedAuthentication;
    }

    /**
     * 这里是判断是否采用该provider的依据
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(TokenBasedAuthentication.class);
    }
}
